package com.only4play.utils;

import com.only4play.auth.AuthenticatedUser;
import com.only4play.constant.SSOConstant;
import com.only4play.domain.model.RpcAccessToken;
import com.only4play.domain.model.SessionAccessToken;
import jakarta.servlet.http.HttpServletRequest;

import java.time.Instant;
import java.util.Optional;

/**
 * @author liyuncong
 * @version 1.0
 * @file SessionUtils
 * @brief sssion工具类
 * @details sssion工具类
 * @date 2023-11-19
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2023-11-19               liyuncong          Created
 */
public class SessionUtils {

    public static SessionAccessToken getAccessToken(HttpServletRequest request) {
        return (SessionAccessToken) request.getSession().getAttribute(SSOConstant.SESSION_ACCESS_TOKEN);
    }

    public static AuthenticatedUser<Void> getUser(HttpServletRequest request) {
        return Optional.ofNullable(getAccessToken(request)).map(RpcAccessToken::getAuthenticatedUser).orElse(null);
    }

    public static String getUserId(HttpServletRequest request) {
        return Optional.ofNullable(getUser(request)).map(AuthenticatedUser::getUserId).orElse(null);
    }

    public static void setAccessToken(HttpServletRequest request, RpcAccessToken rpcAccessToken) {
        SessionAccessToken sessionAccessToken = null;
        if (rpcAccessToken != null) {
            sessionAccessToken = createSessionAccessToken(rpcAccessToken);
        }
        request.getSession().setAttribute(SSOConstant.SESSION_ACCESS_TOKEN, sessionAccessToken);
    }

    private static SessionAccessToken createSessionAccessToken(RpcAccessToken accessToken) {
        long expirationTime = Instant.now().plusSeconds(accessToken.getExpiresIn()).toEpochMilli();
        return new SessionAccessToken(accessToken.getAccessToken(), accessToken.getExpiresIn(),
            accessToken.getRefreshToken(), accessToken.getAuthenticatedUser(), expirationTime);
    }

    public static void invalidate(HttpServletRequest request) {
        setAccessToken(request, null);
        request.getSession().invalidate();
    }
}
